package com.atguigu.juc.date928;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: shenhao
 * @CreatTime: 2024/9/28 22:20
 * @Version: 1.0
 * 重写
 */
public class ReTicketSale {
    public static void main(String[] args) {
        // 先创建资源类
        Ticket ticket = new Ticket();
        //创建线程
        Thread t1 = new Thread(() -> {
            for (int result = 0; result < 50; result++) {
                ticket.saleTicket();
            }
        }, "AA");
        t1.start();
        Thread t2 = new Thread(() -> {
            for (int result = 0; result < 50; result++) {
                ticket.saleTicket();
            }
        }, "BB");
        t2.start();
        Thread t3 = new Thread(() -> {
            for (int result = 0; result < 50; result++) {
                ticket.saleTicket();
            }
        }, "CC");
        t3.start();
    }
}

class Ticket {
    private int count = 50;
    Lock lock = new ReentrantLock(true);

    // 高内聚,低耦合,
    public void saleTicket() {
        lock.lock();
        try {
            if (count > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了第" + (count--) + "张票");
            }
        } finally {
            lock.unlock();
        }
    }
}
